const mongoose = require('mongoose');

const env = process.env.NODE_ENV || 'development';
const config = require('../config.json').mongo[env];

// mongoose
// const DB_URL = `mongodb://${username}:${password}@${hostname}:${port}/${database}`;
const aProduction = ['mongodb://', `${config.username}:${config.password}@`, `${config.host}:${config.port}/${config.database}?authSource=admin`];
const aDevelopment = ['mongodb://', `${config.host}:${config.port}/${config.database}`];
const DB_URL = env === 'development' ? aDevelopment.join('') : aProduction.join('');
// console.log('DB_URL: ', DB_URL);
const options = { // 如不写,会报警告warming
  keepAlive: 1,
  useNewUrlParser: true,
  useUnifiedTopology: true,
  // 使用And连接的sql语句时汇报警告,所以设置'useFindAndModify'为false
  useFindAndModify: false,
};

function connect() {
  mongoose.connection
    .on('error', console.log)
    .on('disconnected', connect)
    .once('open', () => {
      // listen 起服务`app.listen(port);`
      console.log('[mongodb] 连接成功 (^し^)');
    });
  return mongoose.connect(DB_URL, options);
}
/**
 * TODO: 监听
 * const connection = mongoose.connection;
 * connection.on("connected", () => {// 连接成功})
 * connection.on("open", () => {// 数据库开启});
 * connection.on('error', err => {// 链接异常})
 * connection.on('disconnected', () => {// 监听断开链接})
 * mongoose.disconnect(function(){// 主动断开操作})
 */

module.exports = connect;
